package com.pn.warehouse.service.impl;

import com.pn.warehouse.entity.OutStore;
import com.pn.warehouse.entity.Result;
import com.pn.warehouse.mapper.OutStoreMapper;
import com.pn.warehouse.mapper.ProductMapper;
import com.pn.warehouse.page.Page;
import com.pn.warehouse.service.OutStoreService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class OutStoreServiceImpl implements OutStoreService {

    @Resource
    private OutStoreMapper outStoreMapper;

    @Resource
    private ProductMapper productMapper;

    //添加出库单
    @Override
    public Result insertOutStore(OutStore outStore) {
        int i = outStoreMapper.insertOutStore(outStore);
        if (i > 0){
            return Result.ok("出库单添加成功！");
        }
        return Result.err(Result.CODE_ERR_BUSINESS, "出库单添加失败！");
    }

    //分页查询出库单
    @Override
    public Page queryOutStorePage(Page page, OutStore outStore) {
        //1、查询出库单总行数
        int count = outStoreMapper.findOutStoreCount(outStore);

        //2、分页查询出库单
        List<OutStore> outStoreList = outStoreMapper.findOutStorePage(page, outStore);

        //3、封装page并返回
        page.setTotalNum(count);
        page.setResultList(outStoreList);
        return page;
    }

    //确认出库
    @Transactional
    @Override
    public Result outStoreConfirm(OutStore outStore) {
        //1、判断存库数量是否充足
        int invent = productMapper.findInventById(outStore.getProductId());
        if (invent < outStore.getOutNum()){
            return Result.err(Result.CODE_ERR_BUSINESS, "商品存库不足！");
        }

        //2、设置存库剩余量
        int i = productMapper.setInventById(outStore.getProductId(), -outStore.getOutNum());

        //3、设置出库状态
        int j = outStoreMapper.setIsOutById(outStore.getOutsId());

        //4、返回响应
        if (i > 0 && j > 0){
            return Result.ok("出库成功！");
        }
        return Result.err(Result.CODE_ERR_BUSINESS, "出库失败！");
    }

}
